package network;

import java.io.IOException;
import java.net.*;
import java.util.HashMap;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private final String serverIP;//服务器IP
    private final int serverPort;//服务器端口号


    //客户端启动时需要知道服务器在哪里
    public UdpEchoClient(String serverIP,int serverPort ) throws SocketException {
        socket = new DatagramSocket();
        this.serverPort = serverPort;
        this.serverIP = serverIP;
    }
    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);//
        while (true){
            System.out.print("->请输入要翻译的单词");
            String request = scanner.next();
            //此时将这个请求包装一下
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,request.getBytes().length,InetAddress.getByName(serverIP),serverPort);
            //发送这个请求
            socket.send(requestPacket);
            //此时创建一个空碗,接受这个请求
            DatagramPacket responsePacket = new DatagramPacket(new byte[4090],4090);
            socket.receive(responsePacket);//将获取到的处理结果装入这个碗
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.printf(" rep:%s resp: %s\n",request,response);

        }

    }

    public static void main(String[] args) throws IOException {
        //参数IP地址和端口号
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();

    }

}
